package com.example.server;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author bigFish
 * @Title: get接口
 */
@RestController
@RequestMapping("/get")
public class GetMethodController {

    @ApiOperation("添加cookies")
    @GetMapping(value = "/addCookies")
    public String getCookies(HttpServletResponse response) {
        Cookie cookie = new Cookie("user1", "admin");
        response.addCookie(cookie);
        return "已添加Cookies";
    }

    @ApiOperation("判断是否存在cookies")
    @GetMapping("/findCookies")
    public String findCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (Objects.isNull(cookies)) {
            return "请添加Cookies再进行访问";
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            if (!name.equals("user") || !value.equals("admin")) {
                return "failed";
            }
            return "Success";
        }
        return "cookies is null";
    }

    @ApiOperation("通过地址栏传入参数")
    @GetMapping("/list")
    public HashMap<Object, Object> getList(int start, int end) {
        HashMap<Object, Object> list = new HashMap<>(16);
        list.put("张三", 12);
        list.put("李四", 12);
        list.put("赵六", 90);
        list.put("王五", 18);
        return list;
    }

    @ApiOperation("通过地址栏传入变量")
    @GetMapping("/list/{start}/{end}")
    public Map listVi(@PathVariable int start, @PathVariable int end) {
        HashMap<Object, Object> list = new HashMap<>(16);
        list.put("张三",12);
        list.put("李四",12);
        list.put("赵六",90);
        list.put("王五",18);
        return list;
    }
}
